package com.yzy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzy.common.Code;
import com.yzy.entity.SP;
import com.yzy.exception.ServiceException;
import com.yzy.mapper.SPMapper;
import com.yzy.service.ISPService;
import com.yzy.utils.StuTokenUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * SPServiceImpl
 *
 * @author 杨子宇
 * @createTime 2023-04-30
 */
@Service
public class SPServiceImpl extends ServiceImpl<SPMapper, SP> implements ISPService {
    public List<SP> findAll() {
        return list();
    }

    public SP findById(Integer id) {
        return getById(id);
    }

    public void insertOrUpdate(SP sP) {
        if (sP.getId() == null) {
            List<SP> list = list(
                    new QueryWrapper<SP>()
                            .eq("exam_id", sP.getExamId())
                            .eq("student_id", StuTokenUtils.getCurrentStudent().getId())
            );

            if (CollUtil.isNotEmpty(list)){
                throw new ServiceException(Code.code_401,"您已经提交考卷！");
            }

            sP.setTime(DateUtil.now());
            sP.setStudentId(StuTokenUtils.getCurrentStudent().getId());
        }

        saveOrUpdate(sP);
    }

    public boolean deleteById(Integer id) {
        return removeById(id);
    }

    public boolean deleteSPs(List<Integer> ids) {
        return removeByIds(ids);
    }

    public Page<SP> findPage(Integer pageNum, Integer pageSize) {
        Page<SP> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SP> queryWrapper = new QueryWrapper<>();
        return page(page, queryWrapper);
    }
}
